package com.ApiBack.springbootinit.controller;

import com.ApiBack.springbootinit.annotation.AuthCheck;
import com.ApiBack.springbootinit.client.CLient;
import com.ApiBack.springbootinit.common.BaseResponse;
import com.ApiBack.springbootinit.common.DeleteRequest;
import com.ApiBack.springbootinit.common.ErrorCode;
import com.ApiBack.springbootinit.common.ResultUtils;
import com.ApiBack.springbootinit.constant.CommonConstant;
import com.ApiBack.springbootinit.constant.UserConstant;
import com.ApiBack.springbootinit.exception.BusinessException;
import com.ApiBack.springbootinit.exception.ThrowUtils;
import com.ApiBack.springbootinit.model.dto.interfaceinfo.*;
import com.ApiBack.springbootinit.model.entity.*;
import com.ApiBack.springbootinit.model.enums.InterfaceStatus;
import com.ApiBack.springbootinit.service.InterfaceInfoService;
import com.ApiBack.springbootinit.service.UserInterfaceInfoService;
import com.ApiBack.springbootinit.service.UserService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@RestController
@RequestMapping("/interfaceInfo")
@Slf4j
@CrossOrigin(origins = {"http://8.130.82.61","http://124.221.241.140"},allowCredentials = "true")
public class InterfaceController {

    @Resource
    private InterfaceInfoService interfaceInfoService;

    @Resource
    private UserService userService;
    @Resource
    private UserInterfaceInfoService userInterfaceInfoService;

    // region 增删改查

    /**
     * 创建
     *
     * @param interfaceAddRequest
     * @param request
     * @return
     */
    @PostMapping("/add")
    public BaseResponse<Long> addInterfaceInfo(@RequestBody InterfaceAddRequest interfaceAddRequest, HttpServletRequest request) {
        if (interfaceAddRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        InterfaceInfo interfaceInfo = new InterfaceInfo();
        BeanUtils.copyProperties(interfaceAddRequest, interfaceInfo);
        // 校验
        interfaceInfoService.validInterfaceInfo(interfaceInfo, true);
        User loginUser = userService.getLoginUser(request);
        interfaceInfo.setUserId(loginUser.getId());
        boolean result = interfaceInfoService.save(interfaceInfo);
        if (!result) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR);
        }
        long newInterfaceInfoId = interfaceInfo.getId();
        return ResultUtils.success(newInterfaceInfoId);
    }


    /**
     * 删除
     *
     * @param
     * @param request
     * @return
     */
    @PostMapping("/delete")
    public BaseResponse<Boolean> deleteInterfaceInfo(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = userService.getLoginUser(request);
        long id = deleteRequest.getId();
        // 判断是否存在
        InterfaceInfo oldInterfaceInfo = interfaceInfoService.getById(id);
        if (oldInterfaceInfo == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        // 仅本人或管理员可删除
        if (!oldInterfaceInfo.getUserId().equals(user.getId()) && !userService.isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        boolean b = interfaceInfoService.removeById(id);
        return ResultUtils.success(b);

    }

    /**
     * 更新（仅管理员）
     *
     * @param interfaceUpdateRequest
     * @return
     */
    @PostMapping("/update")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> updateInterfaceInfo(@RequestBody InterfaceUpdateRequest interfaceUpdateRequest, HttpServletRequest request) {
        if (interfaceUpdateRequest == null || interfaceUpdateRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        InterfaceInfo interfaceInfo = new InterfaceInfo();
        BeanUtils.copyProperties(interfaceUpdateRequest, interfaceInfo);
        User loginUser = userService.getLoginUser(request);
        ;
        // 参数校验
        interfaceInfoService.validInterfaceInfo(interfaceInfo, false);
        long id = interfaceUpdateRequest.getId();
        // 判断是否存在
        InterfaceInfo oldInterfaceInfo = interfaceInfoService.getById(id);
        ThrowUtils.throwIf(oldInterfaceInfo == null, ErrorCode.NOT_FOUND_ERROR);
        //鉴权,只有管理员和本人才能够修改
        if (!oldInterfaceInfo.equals(loginUser.getId()) && !userService.isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        boolean result = interfaceInfoService.updateById(interfaceInfo);
        return ResultUtils.success(result);
    }

    /**
     * 根据 id 获取
     *
     * @param
     * @return
     */


    @GetMapping("/get")
    public BaseResponse<InterfaceInfo> getInterfaceInfoById(long id) {
        if (id < 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }

        InterfaceInfo interfaceInfo = interfaceInfoService.getById(id);
        interfaceInfo.setUrl("安全考虑，无法告知");
        return ResultUtils.success(interfaceInfo);
    }


    /**
     * 管理员查询
     *
     * @param interfaceInfoQueryRequest
     * @return
     */
    @AuthCheck(mustRole = "admin")
    @GetMapping("/list")
    public BaseResponse<List<InterfaceInfo>> listInterfaceInfo(InterfaceQueryRequest interfaceInfoQueryRequest) {
        InterfaceInfo interfaceInfoQuery = new InterfaceInfo();
        if (interfaceInfoQueryRequest != null) {
            BeanUtils.copyProperties(interfaceInfoQueryRequest, interfaceInfoQuery);
        }
        QueryWrapper<InterfaceInfo> queryWrapper = new QueryWrapper<>(interfaceInfoQuery);
        List<InterfaceInfo> interfaceInfoList = interfaceInfoService.list(queryWrapper);
        return ResultUtils.success(interfaceInfoList);
    }


    /**
     * 分页获取列表（仅管理员）
     *
     * @param
     * @return
     */
    @GetMapping("/list/page")
   // @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Page<InterfaceInfo>> listInterfaceInfoByPage(InterfaceQueryRequest interfaceInfoQueryRequest, HttpServletRequest request) {
        if (interfaceInfoQueryRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        InterfaceInfo interfaceInfoQuery = new InterfaceInfo();
        BeanUtils.copyProperties(interfaceInfoQueryRequest, interfaceInfoQuery);
        long current = interfaceInfoQueryRequest.getCurrent();
        long size = interfaceInfoQueryRequest.getPageSize();
        String sortField = interfaceInfoQueryRequest.getSortField();
        String sortOrder = interfaceInfoQueryRequest.getSortOrder();
        String description = interfaceInfoQuery.getDescription();
        // description 需支持模糊搜索
        interfaceInfoQuery.setDescription(null);
        // 限制爬虫
        if (size > 50) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // todo 接口地址脱敏
        QueryWrapper<InterfaceInfo> queryWrapper = new QueryWrapper<>(interfaceInfoQuery);
        queryWrapper.like(StringUtils.isNotBlank(description), "description", description);
        queryWrapper.orderBy(StringUtils.isNotBlank(sortField),
                sortOrder.equals(CommonConstant.SORT_ORDER_ASC), sortField);
        Page<InterfaceInfo> interfaceInfoPage = interfaceInfoService.page(new Page<>(current, size), queryWrapper);
        return ResultUtils.success(interfaceInfoPage);
    }


    @PostMapping("/online")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> onlineInterfaceInfo(@RequestBody InterfacePublishRequest interfacePublishRequest, HttpServletRequest request) {
        if (interfacePublishRequest == null || interfacePublishRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User loginUser = userService.getLoginUser(request);

        long id = interfacePublishRequest.getId();
        // 判断是否存在
        InterfaceInfo oldInterfaceInfo = interfaceInfoService.getById(id);
        ThrowUtils.throwIf(oldInterfaceInfo == null, ErrorCode.NOT_FOUND_ERROR);
        //鉴权,只有管理员和本人才能够修改
        if (!oldInterfaceInfo.equals(loginUser.getId()) && !userService.isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        //修改接口状态
        InterfaceInfo interfaceInfo = new InterfaceInfo();
        interfaceInfo.setId(id);
        interfaceInfo.setStatus(InterfaceStatus.PUBLISH.getValue());
        boolean result = interfaceInfoService.updateById(interfaceInfo);
        return ResultUtils.success(result);
    }

    @PostMapping("/offline")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> offlineInterfaceInfo(@RequestBody InterfaceOffRequest interfaceOffRequest, HttpServletRequest request) {
        if (interfaceOffRequest == null || interfaceOffRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User loginUser = userService.getLoginUser(request);
        ;
        long id = interfaceOffRequest.getId();
        // 判断是否存在
        InterfaceInfo oldInterfaceInfo = interfaceInfoService.getById(id);
        ThrowUtils.throwIf(oldInterfaceInfo == null, ErrorCode.NOT_FOUND_ERROR);
        //鉴权,只有管理员和本人才能够修改
        if (!oldInterfaceInfo.equals(loginUser.getId()) && !userService.isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        //修改接口状态
        InterfaceInfo interfaceInfo = new InterfaceInfo();
        interfaceInfo.setId(id);
        interfaceInfo.setStatus(InterfaceStatus.OFF.getValue());
        boolean result = interfaceInfoService.updateById(interfaceInfo);
        return ResultUtils.success(result);
    }

    @PostMapping("/invoke")
    public BaseResponse<Object> invokeInterfaceInfo(@RequestBody InterfaceInvokeRequest interfaceInvokeRequest, HttpServletRequest request) {

         /*
        此处调用接口，是用户发起调用接口请求，之后通过Api平台核验，
        通过后Api平台再去调用接口并获取返回结果，
        然后平台再将结果返回给用户。
         */
        //检查请求参数
        User loginUser = userService.getLoginUser(request);
        long id = interfaceInvokeRequest.getId();

        if (interfaceInvokeRequest == null || interfaceInvokeRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }

        //todo 检查接口是否存在
        InterfaceInfo interfaceInfo = interfaceInfoService.getById(id);
        if (interfaceInfo==null)
        {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR,"接口不存在");
        }

        // todo 获取参数
        String userRequestParams = interfaceInvokeRequest.getUserRequestParams();


        //todo 判断接口状态
        if ((interfaceInfo.getStatus()==InterfaceStatus.OFF.getValue()))
        {
            throw new BusinessException(ErrorCode.OPERATION_ERROR,"接口已下线");
        }

        //todo 检查调用者是否还有调用次数
        QueryWrapper<UserInterfaceInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("interfaceInfoId", id);
        queryWrapper.eq("userId", loginUser.getId());
        UserInterfaceInfo userInterfaceInfo = userInterfaceInfoService.getBaseMapper().selectOne(queryWrapper);

        if (userInterfaceInfo==null)
        {

            try {
                UserInterfaceInfo userInterfaceInfo1 = new UserInterfaceInfo();
                userInterfaceInfo1.setUserId(loginUser.getId());
                userInterfaceInfo1.setInterfaceInfoId(id);
                userInterfaceInfo1.setLeftNum(9);
                userInterfaceInfo1.setTotalNum(1);
                userInterfaceInfoService.getBaseMapper().insert(userInterfaceInfo1);
            } catch (Exception e) {
                log.error("数据库操作失败",e);
            } finally {

            }
        }

        else {
            Integer leftNum = userInterfaceInfo.getLeftNum();
            if (leftNum<=0)
            {
                throw new BusinessException(ErrorCode.NO_AUTH_ERROR,"您的剩余调用次数不足");
            }
        }

        //todo 获取接口地址
        String url = interfaceInfo.getUrl();
        log.info("接口地址:" + url);

        // todo 获取用户校验信息
        String accessKey = loginUser.getAccessKey();
        String secretKey = loginUser.getSecretKey();
        // todo 创建一个客户端(new Client(accessKey,secretKey,url))，然后客户端再去查库验证身份，并且将接口url传给客户端
        // String invokeParams = interfaceInvokeRequest.getInvokeParams();

        //todo 获取返回结果
        String result="";

        //todo 项目难点之一，如何根据用户输入的不同地址来调用不同的接口以及正确的输入相应的参数
        CLient cLient = new CLient(accessKey, secretKey);
        if (id==1)
        {

           /* Gson gson = new Gson();
            UserTest userTest = gson.fromJson(userRequestParams, UserTest.class);*/
            UserTest userTest = new UserTest();
            userTest.setName(userRequestParams);
            result = cLient.invokeApi(userTest, url);
        } else if (id==2) {

            result=cLient.getPoisonousChickenSoup(url);

        } else if (id==3) {

            result=cLient.getLocalWeather(url);

        } else if (id==4) {

            Location location = new Location();
            location.setLocation(userRequestParams);
            System.out.println(location);
            result=cLient.getWeatherByLocation(url, location);

        } else if (id==5) {

            result=cLient.getJoke(url);

        } else if (id==6) {

            result=cLient.getEnglish(url);

        } else if (id==7) {

            result=cLient.getWallpaper(url);
        }

        return ResultUtils.success(result);

    }
    }

